#!/usr/bin/python

########################################################################################
#
# Coronary - A wrapper script for Filippo Valsorda's Heartbleed tool
# that provides functionality for checking multiple hosts.
#
# Usage - ./coronary.py -i [input_csv] -o [output_csv]
#
# Input CSV Format - [host],[service],[port]
# Output CSV Format - [host],[service],[port],[vulnerability status],[date],[time]
# 
# Copyright (c) 2014, Harrison Sand <h.sand01@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, 
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this 
#    list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice, 
#    this list of conditions and the following disclaimer in the documentation 
#    and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
# POSSIBILITY OF SUCH DAMAGE.
#
########################################################################################


import argparse, csv, subprocess, datetime

def returncode_interpreter(code):
    if code == 0:
        return("SAFE")
    if code == 1:
        return("VULNERABLE")
    if code == 2:
        return("ERROR")

parser = argparse.ArgumentParser()
parser.add_argument('-i','--input', help='Input CSV',required=True)
parser.add_argument('-o','--output',help='Output CSV', required=True)
args = parser.parse_args()

try:
    input_csv = open(args.input,"rb")
    reader = csv.reader(input_csv)
    output_csv = open(args.output,"wb")
    writer = csv.writer(output_csv)
    for in_row in reader:
        proc = subprocess.Popen(["./Heartbleed", "-service="+in_row[1], in_row[0]+":"+in_row[2]])
        proc.wait()
        now = datetime.datetime.now()
        writer_data = [in_row[0], in_row[1], in_row[2], returncode_interpreter(proc.returncode), now.strftime("%Y/%m/%d"), now.strftime("%H:%M:%S")]
        writer.writerow(writer_data)
finally:
    input_csv.close()